// pages/mine/index.js
const Cloud = require('../../sdk/av-core-min')
Page({

    /**
     * 页面的初始数据
     */
    data: {
        userInfo:null,
        bookCode:''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let {userInfo} = getApp().globalData
        this.setData({userInfo})
    },
    handleCall(){
        wx.makePhoneCall({
          phoneNumber: '02366668888',
        })
    },
    handleQrCode(){
        wx.scanCode({
          success:(res)=>{
              console.log(res);
              this.setData({
                  bookCode:res.result
              })
          }
        })
    },
    handleSubscribe(){ //订阅消息
      wx.requestSubscribeMessage({
        tmplIds:['pB2U2xhgsNuE70yMFGWbeEO-CiGZr6H4I8SLwkM_iaE','cI3F6FmTkhrX232xPoiyU6yz-KaVli18xorwAVVu-BY'], //配置的订阅模板id
        success:(res)=>{
          console.log(res);
        }
      })
    },
    async handleSend(){ //发送消息，逻辑代码一般要放在后端
      // 1. 获取access_token
      let token_url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx759ba279af47d3bb&secret=9af3ed1fb56980c6b34cd2b94c2652db`
      let token = await getApp().fly.get(token_url)
      console.log(token);
      let {access_token} = token.data
      // 2. 向订阅者发送消息
      let send_url = `https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${access_token}`
      // 开奖时间{{date3.DATA}}
      // 活动名称{{thing5.DATA}}
      // 奖品名称{{thing8.DATA}}
      getApp().fly.post(send_url,{
        "touser": "olN8Y0W1ZVWIjxdwPYxOgG2SNOKY", //订阅者的openid,跟订单id绑定的用户openid
        "template_id": "pB2U2xhgsNuE70yMFGWbeEO-CiGZr6H4I8SLwkM_iaE", //使用的消息模板id
        "page": "/pages/read/index", //用户点击消息面板后跳转的页面
        "miniprogram_state":"trial",  //跳转的小程序类型，开发、体验、正式
        "lang":"zh_CN",
        "data": { //需要跟消息模板字段对应的数据包
            "thing5": {
                "value": "500万彩票大奖"
            },
            "date3": {
                "value": "2015年01月05日"
            },
            "thing8": {
                "value": "应该是现金奖励"
            } 
        }
      }).then(res=>{
        console.log(res);
      })
    },
    handleQuickLogin(){
        Cloud.User.loginWithMiniApp().then(user => {
            console.log('一键登录成功',user);
            let {attributes,id} = user
            attributes.userid = id
            getApp().globalData.userInfo = attributes //全局存放用户信息
            wx.setStorage({ //本地存储
                key:'userInfo',
                data:attributes
            })
            this.setData({userInfo:attributes}) //本页面响应式
        }).catch(console.error);
    },
    handleLogout(){
        getApp().globalData.userInfo = null //修改全局
        wx.removeStorage({ //清除本地存储
          key: 'userInfo',
        })
        this.setData({userInfo:null}) //本页面响应式
    },
    onShareAppMessage() { //自定义分享
      return {
        title:'一起来阅读吧！',
        path:'/pages/read/index',
        imageUrl:'/assets/book/book10.jpg'
      }
    }
})